﻿using AutoMapper;
using MediatR;
using SupplyChain.Domain.Entities;
using SupplyChain.Infrastructure.Interface;
using SupplyChain.Write.API.Application.Command.PurchaseOrder;

namespace SupplyChain.Write.API.Application.CommandHandler.PurchaseOrder
{
    public class AddPurchaseOrderHandler : IRequestHandler<AddPurchaseOrderCommand, bool>
    {
        private readonly IBaseRepository<Domain.Entities.PurchaseOrder> repository;
        private readonly IBaseRepository<PurchaseOrderDetail> detailRep;
        private readonly IMapper mapper;

        public AddPurchaseOrderHandler(IBaseRepository<Domain.Entities.PurchaseOrder> repository, IBaseRepository<PurchaseOrderDetail> detailRep, IMapper mapper)
        {
            this.repository = repository;
            this.detailRep = detailRep;
            this.mapper = mapper;
        }

        public async Task<bool> Handle(AddPurchaseOrderCommand request, CancellationToken cancellationToken)
        {
            Domain.Entities.PurchaseOrder order = mapper.Map<Domain.Entities.PurchaseOrder>(request);
            order = await repository.AddReturnEntityAsync(order);
            order.Details = mapper.Map<List<PurchaseOrderDetail>>(request.Detail);
            bool result = true;
            if (order.Id != 0 && order.Details != null && order.Details.Count > 0)
            {
                foreach (PurchaseOrderDetail detail in order.Details)
                {
                    detail.PuId = order.Id;
                }
                result = await detailRep.AddRangeAsync(order.Details);
            }
            return await Task.FromResult(result);
        }
    }
}
